<template>
  <div class="page luckdraw-detail">
    <div class="luckdraw-detail-container">
      <list-item v-if="pageData.activity.activity_id" :listData="pageData.activity"
        :hasMarginBottom="false" :showCreater="false" :isLink="false" :isSwipper="true" :canPreview="true"></list-item>
      <div class="notice">
        <notice-list :listData="noticeList"></notice-list>
      </div>
      <div class="support" v-if="pageData.activity.creater_nickname" @click="onCreaterClick">
        <div class="link-content">
          <div class="left">
            <h4>发起人</h4>
          </div>
          <div class="right" :class="{ 'is-link': createrInfo.wechatName !== ''}">
            {{pageData.activity.creater_nickname}}
            <img v-if="pageData.activity.creater_headimgurl" :src="pageData.activity.creater_headimgurl"/>
          </div>
        </div>
      </div>
      <div class="address-list-entrance" v-if="showAddressListEntrance">
        <m-link
          title="查看中奖者收货信息"
          isLast
          @on-click="onShowAddressList">
        </m-link>
      </div>
      <div class="quote" v-if="pageData.activity.recommend">
        <p>{{pageData.activity.recommend}}</p>
      </div>
      <div class="result-section" v-if="showSuccessResult || showFailResult">
        <div class="box">
          <div v-if="showSuccessResult">
            <i class="icon icon-success"></i>
            <p class="result-title red">恭喜你，中奖了</p>
            <p class="award-code">我的抽奖码：<span>{{awardCode}}</span></p>
            <div class="copy-code" @click="onCopyAwardCodeClick">复制抽奖码</div>
            <div class="success-btn">
              <div class="btn-inner">
                <m-button text="填写地址" @onClick="onAddressEditClick"></m-button>
              </div>
              <div class="btn-inner">
                <m-button text="炫耀一下" type="plain" @onClick="onShareClick"></m-button>
              </div>
            </div>
          </div>
          <div v-if="showFailResult">
            <i class="icon icon-fail"></i>
            <p class="result-title">很遗憾，你未中奖</p>
          </div>
          <a class="more-public" @click="onMoreLuckListClick">查看更多公共抽奖 ></a>
          <div class="win-info">
            <div class="win-title">
              <hr>
              <span>中奖者名单</span>
              <hr>
            </div>
            <div class="win-list">
              <div v-for="(item, i) in winPlayer" :key="i">
                <div class="image">
                  <img :src="item.headimgurl" :class="{ 'has-bg': !item.headimgurl }" :style="!item.headimgurl && imageMissBg"/>
                  <template v-if="pageData.activity.award_amount_second || pageData.activity.award_amount_third">
                    <i class="award-rank" v-if="item.award === 1" :style="awardRankBg1"></i>
                    <i class="award-rank" v-if="item.award === 2" :style="awardRankBg2"></i>
                    <i class="award-rank" v-if="item.award === 3" :style="awardRankBg3"></i>
                  </template>
                </div>
                <div class="nick">{{item.nickname || '无名氏'}}</div>
              </div>
            </div>
            <a class="more-winner" @click="onShowAllWinnerClick">查看全部中奖名单 ></a>
          </div>
        </div>
      </div>
      <div class="join">
        <form @submit="onJoinBtnClick" report-submit="true">
          <div class="join-btn" :class="{ waiting: isWaiting, gray: !canJoin }"
            v-if="pageData.activity.status === 1">
            <button v-if="isWaiting">待开奖</button>
            <button v-else formType="submit">参与抽奖</button>
          </div>
        </form>
        <p v-if="pageData.activity.activity_id">{{totalPlayerTip}} {{totalPlayerNumber}} 人参与，<a @click="onMorePartnerClick">查看全部 &gt;</a></p>
        <div class="avatar">
          <img v-for="(item, i) in lastPlayer" :key="i" :src="item.headimgurl"
            :class="{ 'has-bg': !item.headimgurl }" :style="!item.headimgurl && imageMissBg"/>
        </div>
      </div>
      <div class="detail-section" v-if="pageData.activity.describe || extendData.tuwenDetail && extendData.tuwenDetail.length > 0">
        <div class="title">
          <hr>
          <span>了解更多</span>
          <hr>
        </div>
        <div class="content" v-if="pageData.activity.describe">
          {{pageData.activity.describe}}
        </div>
        <div class="content" v-else>
          <div v-for="(item, i) in extendData.tuwenDetail" :key="i" class="content-item">
            <p v-if="item.type === 'text' && item.content">{{item.content}}</p>
            <img v-if="item.type === 'image' && item.content" :src="item.content" mode="widthFix"/>
          </div>
        </div>
      </div>
      <!-- 进行中 -->
      <div class="btn-section" v-if="pageData.activity.status === 1">
        <div class="btn-inner">
          <m-button text="分享赚金币" @onClick="onShareClick"></m-button>
        </div>
        <div class="btn-inner">
          <m-button text="我也要发起抽奖" type="plain" @onClick="onAddAwardClick"></m-button>
        </div>
      </div>
      <!-- 已结束 -->
      <div class="btn-section" v-if="pageData.activity.status === 2">
        <div class="btn-inner">
          <m-button v-if="pageData.activity.is_creater" text="再发起一个抽奖" type="red" @onClick="onAddAwardClick"></m-button>
          <m-button v-else text="我也要发起抽奖" type="red" @onClick="onAddAwardClick"></m-button>
        </div>
      </div>
      <back-home v-if="showBackHome"></back-home>
    </div>
    <m-dialog
      :show.sync="showCreaterDialog"
      title="发起人微信"
      :content="[`昵称：${pageData.activity.creater_nickname}`, `微信号：${createrInfo.wechatName}`]"
      :avatar="pageData.activity.creater_headimgurl"
      button="一键复制微信号"
      @onClick="onCreaterWechatCopyClick"></m-dialog>
    <m-actionsheet :show.sync="showShareActionsheet" :listData="shareActionsheetListData" @select="onShareSelect"></m-actionsheet>
    <award-code-dialog :show.sync="showAwardCodeDialog" :code="awardCode" @onShareClick="onAwardCodeShareClick"></award-code-dialog>
  </div>
</template>

<script>
import MButton from 'comp/m-button'
import ListItem from 'comp/list-item'
import mixins from 'comp/mixins'
import MLink from 'comp/m-link'
import MDialog from 'comp/m-dialog'
import BackHome from 'comp/back-home'
import MActionsheet from 'comp/m-actionsheet'
import AwardCodeDialog from 'comp/award-code-dialog'
import NoticeList from 'comp/notice-list'
import { apiDomain } from '@/utils/constant'

export default {
  mixins: [mixins],
  components: {
    MButton,
    ListItem,
    MLink,
    MDialog,
    BackHome,
    MActionsheet,
    AwardCodeDialog,
    NoticeList
  },
  data () {
    return {
      authSign: true,
      openId: '',
      shareId: '',
      isWaiting: false,
      pageData: {
        activity: {},
        in: []
      },
      activityId: '',
      lastPlayer: [], // 最近的7个玩家
      totalPlayerNumber: 0,
      totalPlayerTip: '已有',
      showSuccessResult: false,
      showFailResult: false,
      winPlayer: [],
      showAddressListEntrance: false,
      showCreaterDialog: false,
      createrInfo: {},
      showBackHome: false,
      icons: {
        info: `${require('static/images/info.png')}`,
        imageMissBg: `${require('static/images/image-miss-bg.png')}`,
        awardRank1: `${require('static/images/award-rank1.png')}`,
        awardRank2: `${require('static/images/award-rank2.png')}`,
        awardRank3: `${require('static/images/award-rank3.png')}`
      },
      awardCode: '', // 我的抽奖码
      showShareActionsheet: false,
      shareActionsheetListData: [
        {
          text: '邀请微信好友',
          type: 'share'
        },
        {
          text: '生成邀请海报'
        }
      ],
      showAwardCodeDialog: false,
      noticeList: [],
      canJoin: true // 是否符合参与条件，默认为true，可以参与
    }
  },
  computed: {
    imageMissBg () {
      return `background-image: url(${this.icons.imageMissBg});`
    },
    awardRankBg1 () {
      return `background-image: url(${this.icons.awardRank1});`
    },
    awardRankBg2 (i) {
      return `background-image: url(${this.icons.awardRank2});`
    },
    awardRankBg3 () {
      return `background-image: url(${this.icons.awardRank3});`
    },
    awardTime () {
      let output
      const time = this.pageData.activity.award_time
      if (time) {
        output = this.timeFilter(time)
      }
      return output
    },
    extendData () {
      let output
      if (this.pageData.activity.data && this.pageData.activity.data.indexOf('{') > -1) {
        output = JSON.parse(this.pageData.activity.data)
      } else {
        output = {}
      }
      return output
    }
  },
  async onShow () {
    // 只在未授权时执行onShow
    if (!this.authSign) {
      // 检查用户授权
      const authResult = await this.checkAuth()
      if (authResult) {
        this.resetData()
        this.init()
      } else {
        this.authSign = false
      }
    }
  },
  async mounted () {
    this.resetData()
    // 检查用户授权
    const authResult = await this.checkAuth()
    if (authResult) {
      this.init()
    } else {
      this.authSign = false
    }
  },
  methods: {
    async init () {
      const query = this.$root.$mp.query
      this.activityId = query.activityId || query.scene
      this.showBackHome = query.from === 'share'
      this.shareId = query.shareId

      this.openId = await this.getOpenId()

      // 获取活动详情
      await this.getActivityDetail()
      // 判断参与条件
      await this.checkJoinCondition()

      // 获取最近的7个参与者
      this.getLastPlayer()
      // 获取消息列表
      this.getNoticeList()
      // 检查小程序更新
      this.checkUpdate()
    },
    /**
     * 获取活动详情
     */
    async getActivityDetail () {
      const ret = await this.$store.dispatch('getActivityDetail', {
        activityid: this.activityId,
        playerid: this.openId
      })
      this.pageData = ret
      const _in = this.pageData.in[this.activityId] || {}
      // 是否已参与
      if (_in.activity_id) {
        this.isWaiting = true
        this.awardCode = _in.code
      }
      // 活动已结束或其他（非进行中）
      if (this.pageData.activity.status !== 1) {
        // 是否由本人发起的活动，此时要显示“查看中奖者收获信息”入口
        if (this.pageData.activity.is_creater) {
          this.showAddressListEntrance = true
        }
        // 是否已中奖，包括抽中和未抽中
        if (_in.is_winner === 1) {
          // 中奖
          this.showSuccessResult = true
        } else if (_in.is_winner === 2) {
          // 未中奖
          this.showFailResult = true
        }
        this.totalPlayerTip = '感谢'
        this.getWinPlayer()
      }
      if (this.pageData.activity.info) {
        this.createrInfo = JSON.parse(this.pageData.activity.info)
      }
    },
    /**
     * 判断参与条件
     */
    async checkJoinCondition () {
      const condition = this.extendData.joinCondition
      let modalText
      if (condition && condition.length > 0) {
        const conditionKey = condition[0].key
        const ret = await this.$store.dispatch('getPlayerInfo', {
          noToast: true,
          playerid: this.openId
        })
        // 不满足抽奖参与条件，返回首页参与更多抽奖
        switch (conditionKey) {
          case 'has_phone':
            if (!ret.phone) {
              // 无绑定手机，不符合条件
              modalText = '无绑定手机号，不符合参与条件'
            }
            break
          case 'is_leader':
            if (ret.children_count === 0) {
              // 无下级，不符合条件
              modalText = '无邀请过下级，不符合参与条件'
            }
            break
          case 'join_30':
            if (ret.activity_count < 30) {
              // 参与次数小于30次，不符合条件
              modalText = '参与次数小于30次，不符合参与条件'
            }
            break
        }
        if (modalText) {
          this.canJoin = false
          wx.showModal({
            title: '提示',
            content: modalText,
            showCancel: false
          })
        }
      }
    },
    /**
     * 获取中奖的名单
     */
    async getWinPlayer () {
      const ret = await this.$store.dispatch('getActivityPlayer', {
        noToast: true,
        activityid: this.activityId,
        rows: 9, // 默认显示9个中奖名单，多于9个则显示 查看更多按钮
        iswinner: 1
      })
      this.winPlayer = ret.list
    },
    /**
     * 获取最近的7个参与者
     */
    async getLastPlayer () {
      const ret = await this.$store.dispatch('getActivityPlayer', {
        noToast: true,
        activityid: this.activityId,
        page: 1,
        rows: 7
      })
      this.lastPlayer = ret.list
      this.totalPlayerNumber = ret.count
    },
    onMorePartnerClick () {
      wx.navigateTo({
        url: `/pages/partner/main?activityId=${this.activityId}`,
      })
    },
    onAddAwardClick () {
      wx.navigateTo({
        url: '/pages/add/main',
      })
    },
    /**
     * 点击参与抽奖
     */
    async onJoinBtnClick (e) {
      if (this.isWaiting || !this.canJoin) {
        return
      }
      if (this.pageData.activity.is_public === 1) {
        const ret = await this.$store.dispatch('queryConfig')
        wx.showModal({
          title: '提示',
          content: `参与抽奖将消耗${ret.goldJoinActivity}个金币`,
          showCancel: true,
          success: (res) => {
            if (res.confirm) {
              this.doJoin(e)
            }
          }
        })
      } else {
        this.doJoin(e)
      }
    },
    /**
     * 提交参与抽奖
     */
    async doJoin (e) {
      const ret = await this.$store.dispatch('joinActivity', {
        activityid: this.activityId,
        playerid: this.openId,
        formid: e.target.formId,
        shareid: this.shareId
      })
      this.isWaiting = true
      this.awardCode = ret.result
      // 显示抽奖码弹窗
      this.showAwardCodeDialog = true
      // 更新参与人列表
      this.getLastPlayer()
    },
    /**
     * 查看更多公共抽奖
     */
    onMoreLuckListClick () {
      wx.reLaunch({
        url: '/pages/index/main'
      })
    },
    /**
     * 填写地址（中奖时）
     */
    onAddressEditClick () {
      wx.navigateTo({
        url: `/pages/address-edit/main?activityId=${this.activityId}&awardTime=${this.pageData.activity.award_time}`
      })
    },
    /**
     * 查看中奖者收货信息
     */
    onShowAddressList () {
      wx.navigateTo({
        url: `/pages/address-list/main?activityId=${this.activityId}`,
      })
    },
    /**
     * 点击发起人，查看发起人微信信息
     */
    onCreaterClick () {
      if (this.createrInfo.wechatName !== '') {
        this.showCreaterDialog = true
      }
    },
    /**
     * 复制发起人的微信号
     */
    onCreaterWechatCopyClick () {
      wx.setClipboardData({
        data: this.createrInfo.wechatName,
        success: (res) => {
          wx.showToast({
            title: '复制成功'
          })
        }
      })
    },
    /**
     * 查看所有中奖名单
     */
    onShowAllWinnerClick () {
      const isMultiRank = (this.pageData.activity.award_amount_second || this.pageData.activity.award_amount_third) ? 1 : 0
      wx.navigateTo({
        url: `/pages/partner/main?activityId=${this.activityId}&isWinner=1&isMultiRank=${isMultiRank}`,
      })
    },
    /**
     * 我要分享或炫耀一下，拉起分享选择菜单
     */
    onShareClick () {
      this.showShareActionsheet = true
    },
    /**
     * 选中分享菜单
     */
    onShareSelect (i) {
      if (i === 1) {
        // 邀请海报
        const listData = this.pageData.activity
        const url = encodeURIComponent(listData.award_image || (this.extendData.awardImageList && this.extendData.awardImageList[0]))
        const title = encodeURIComponent(listData.award_title)
        const detail = encodeURIComponent(listData.type === 1 ? `${this.awardTime}自动开奖` : `参与者达到${listData.award_people}人时 自动开奖`)
        const copywriting = this.showSuccessResult ? encodeURIComponent('耶！我中奖了，邀请你来围观一下') : encodeURIComponent('我正在参与抽奖，邀请你也来参加')
        const scene = encodeURIComponent(listData.activity_id)
        const page = encodeURIComponent(`pages/detail/main`)
        const type = encodeURIComponent('自动开奖')

        const posterUrl = encodeURIComponent(`${apiDomain}/poster/invite?url=${url}&title=${title}&type=${type}&detail=${detail}&copywriting=${copywriting}&page=${page}&scene=${scene}`)
        wx.navigateTo({
          url: `/pages/invite-poster/main?posterUrl=${posterUrl}`,
        })
      }
    },
    /**
     * 复制抽奖码
     */
    onCopyAwardCodeClick () {
      wx.setClipboardData({
        data: this.awardCode,
        success: (res) => {
          wx.showToast({
            title: '复制成功'
          })
        }
      })
    },
    /**
     * 获取消息列表
     */
    async getNoticeList () {
      const ret = await this.$store.dispatch('getNewsList', {
        page: 1,
        rows: 30
      })
      this.noticeList = ret
    },
    /**
     * 抽奖码显示面板上的分享按钮
     */
    onAwardCodeShareClick () {
      this.showAwardCodeDialog = false
      this.showShareActionsheet = true
    }
  },
  onShareAppMessage () {
    return {
      title: `邀请你参与[${this.pageData.activity.award_title}]抽奖`,
      path: `/pages/detail/main?activityId=${this.activityId}&from=share&shareId=${this.openId}`
    }
  }
}
</script>

<style lang="less" scoped>
.luckdraw-detail {
  &-container {
    padding-bottom: 146rpx;
  }
  .notice {
    position: fixed;
    width: 470rpx;
    top: 30rpx;
    left: 24rpx;
    z-index: 10;
  }
  .support {
    position: relative;
    padding-left: 30rpx;
    background-color: #fff;
    &:active {
      background: #d8d8d8;
    }
    .link-content {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 100rpx;
      padding-right: 30rpx;
      border-top: 1rpx solid #e6ebf0;
      .left {
        display: flex;
        align-items: center;
        h4 {
          font-size: 32rpx;
          color: #333;
        }
      }
      .right {
        display: flex;
        align-items: center;
        position: relative;
        font-size: 32rpx;
        color: #333;
        &.is-link {
          padding-right: 32rpx;
        }
        &.is-link::after {
          content: " ";
          display: block;
          height: 12rpx;
          width: 12rpx;
          border-width: 4rpx 4rpx 0 0;
          border-color: #cacaca;
          border-style: solid;
          transform: matrix(0.71, 0.71, -0.71, 0.71, 0, 0);
          position: absolute;
          top: 50%;
          right: 0;
          margin-top: -4rpx;
        }
        img {
          display: block;
          width: 36rpx;
          height: 36rpx;
          margin-left: 14rpx;
        }
      }
    }
  }
  .address-list-entrance {
    margin-top: 20rpx;
  }
  .quote {
    padding: 40rpx 30rpx 30rpx;
    margin-top: 20rpx;
    color: #695d4d;
    background-color: #fef7e5;
    font-size: 30rpx;
    border-top: 1rpx solid #e9e2d0;
    border-bottom: 1rpx solid #e9e2d0;
    p {
      position: relative;
      padding-left: 34rpx;
      line-height: 1.5;
      &:before {
        display: block;
        position: absolute;
        top: -10rpx;
        left: 0;
        content: " ";
        width: 20rpx;
        height: 20rpx;
        background: url("../../../static/images/quote.png") no-repeat center center;
        background-size: contain;
      }
    }
  }
  .result-section {
    background-color: #fff;
    margin-top: 20rpx;
    padding: 30rpx 30rpx;
    .box {
      border: 2rpx solid #cfc296;
      padding: 60rpx 0;
    }
    .icon {
      display: block;
      width: 128rpx;
      height: 128rpx;
      margin: 0 auto;
      &.icon-fail {
        background: url("../../../static/images/face-fail.png") no-repeat center center;
        background-size: contain;
      }
      &.icon-success {
        background: url("../../../static/images/face-success.png") no-repeat center center;
        background-size: contain;
      }
    }
    .result-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #7a7a7a;
      text-align: center;
      margin-top: 30rpx;
      &.red {
        color: #e0382f;
      }
    }
    .award-code {
      font-size: 32rpx;
      color: #e62e8b;
      text-align: center;
      font-weight: bold;
      padding-top: 40rpx;
    }
    .copy-code {
      font-size: 30rpx;
      color: #488ff0;
      text-align: center;
      margin-top: 30rpx;
    }
    .more-public {
      font-size: 30rpx;
      color: #488ff0;
      text-align: center;
      margin-top: 40rpx;
    }
    .more-winner {
      font-size: 30rpx;
      color: #488ff0;
      text-align: center;
      margin-top: 60rpx;
    }
    .success-btn {
      display: flex;
      padding: 50rpx 50rpx 0;
      .btn-inner {
        flex: 1;
        padding-right: 20rpx;
        &:last-child {
          padding-right: 0;
        }
      }
    }
    .win-title {
      display: flex;
      align-items: center;
      padding: 60rpx 50rpx 20rpx;
      font-size: 32rpx;
      color: #777;
      text-align: center;
      hr {
        flex: 1;
        height: 1rpx;
        background: #e6ebf0;
      }
      span {
        flex: 1;
      }
    }
    .win-list {
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
      & > div {
        width: 100% / 3;
        margin-top: 40rpx;
      }
      .image {
        position: relative;
        width: 100rpx;
        margin: 0 auto;
        img {
          display: block;
          width: 100rpx;
          height: 100rpx;
          border: 1rpx solid #e6ebf0;
          &.has-bg {
            background-size: 53rpx 41rpx;
            background-repeat: no-repeat;
            background-position: center center;
            background-color: #fff;
          }
        }
        .award-rank {
          position: absolute;
          top: -40rpx;
          right: -40rpx;
          display: block;
          width: 64rpx;
          height: 64rpx;
          background-size: contain;
          background-repeat: no-repeat;
          background-position: center center;
        }
      }
      .nick {
        color: #333;
        padding-top: 16rpx;
        font-size: 30rpx;
        width: 100rpx;
        margin: 0 auto;
        overflow:hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 1;
        text-align: center;
      }
    }
  }
  .join {
    .join-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 250rpx;
      height: 250rpx;
      border-radius: 50% 50%;
      background-color: #d35346;
      margin: 60rpx auto 0;
      button {
        font-size: 36rpx;
        color: #fff;
        background-color: transparent;
        border: none;
        width: 250rpx;
        height: 250rpx;
        line-height: 250rpx;
        border-radius: 50% 50%;
        padding: 0;
        &::after {
          display: none;
        }
      }
      &.waiting {
        button {
          color: rgba(255, 255, 255, .6);
        }
      }
      &.gray {
        opacity: 0.6;
      }
    }
    p {
      text-align: center;
      font-size: 30rpx;
      color: #777;
      padding-top: 40rpx;
      a {
        display: inline;
        color: #488ff0;
      }
    }
    .avatar {
      display: flex;
      justify-content: center;
      padding-top: 40rpx;
      padding-bottom: 40rpx;
      img {
        display: block;
        width: 66rpx;
        height: 66rpx;
        margin-right: 10rpx;
        border: 1rpx solid #e6ebf0;
        &.has-bg {
          background-size: 40rpx 31rpx;
          background-repeat: no-repeat;
          background-position: center center;
          background-color: #fff;
        }
      }
    }
  }
  .detail-section {
    margin-top: 20rpx;
    padding: 30rpx 30rpx 50rpx;
    background-color: #fff;
    .title {
      display: flex;
      align-items: center;
      padding: 20rpx 50rpx 30rpx;
      font-size: 32rpx;
      color: #777;
      text-align: center;
      hr {
        flex: 1;
        height: 1rpx;
        background: #e6ebf0;
      }
      span {
        flex: 1;
      }
    }
    .content {
      font-size: 30rpx;
      color: #333;
      line-height: 1.5;
      &-item {
        &:not(:last-child) {
          padding-bottom: 30rpx;
        }
      }
      img {
        display: block;
        width: 100%;
      }
    }
  }
  .btn-section {
    position: fixed;
    bottom: 0;
    display: flex;
    width: 100%;
    height: 126rpx;
    background-color: #fff;
    border-top: 1rpx solid #ddd;
    .btn-inner {
      flex: 1;
      padding: 20rpx 20rpx;
      &:nth-child(2) {
        padding-left: 0;
      }
    }
  }
}
</style>
